'use strict'

myApp.controller('InboxCtrl', ['$scope', function ($scope) {

    // modal
    $scope.open = function () {
        $scope.shouldBeOpen = true;
    };

    $scope.close = function () {
        $scope.closeMsg = 'I was closed at: ' + new Date();
        $scope.shouldBeOpen = false;
    };
    // end modal

    $scope.recentMail = [
        { type:'unread', from:'Phil Jenkins', msg:'Your password will expire in 23 days' },
        { type:'unread', from:'Paul Terry', msg:'CRM system updated.' },
        { type:'read', from:'Matt Lundquist', msg:'Successfully deployed Oracle 11g' },
        { type:'read', from:'Lindsay Dugan', msg:'Closed support ticket #4455' },
        { type:'read', from:'Lindsay Dugan', msg:'Reminder: Offsite in San Diego (comicon)' }
    ];

    $scope.closeMail = function (index) {
        //console.log("closing mail " + index);
        $scope.recentMail.splice(index, 1);
    };

}]);

myApp.controller('GroupsCtrl', ['$scope', '$dialog', function ($scope, $dialog) {

	$scope.deleteNode = function (data) {
		var i = 0;
		var deleteNode = -1;
		for(i; i<data.parent.nodes.length; i++){
			if(data.parent.nodes[i] == data)
				deleteNode = i;
		}
		if(deleteNode > -1){
			data.parent.nodes.splice(deleteNode,1);
			data = null;
		}
	    
	};
	$scope.addNode = function (data, name) {
	    var newName = name;
	    data.nodes.push({name:newName, nodes:[], parent:data});
	};
	$scope.tree = [
	    {name:"Groepen", nodes:[], parent:null}
	];
	
	 $scope.opts = {
			    backdrop: true,
			    keyboard: true,
			    backdropClick: true,
			    templateUrl:  'templates/dialogs/addGroupDialog.html', // OR: templateUrl: 'path/to/view.html',
			    controller: 'CloseDialogController'
			  };
	 
	 $scope.deleteOpts = {
			    backdrop: true,
			    keyboard: true,
			    backdropClick: true,
			    templateUrl:  'templates/dialogs/confirmDeleteDialog.html', // OR: templateUrl: 'path/to/view.html',
			    controller: 'CloseDialogController'
			  };
	 
	
	
	$scope.openAddGroupBox = function(data){
		var d = $dialog.dialog($scope.opts);
	      d.open()
	      .then(function(result){
	    	  if(result)
	    		  $scope.addNode(data, result);
	    });
	  };
	  
	  
	  $scope.confirmDeleteGroupBox = function(data){
			var d = $dialog.dialog($scope.deleteOpts);
		      d.open()
		      .then(function(result){
		    	  if(result)
		    		  $scope.deleteNode(data);
		    });
		  };

}]);

myApp.controller('SupplierCtrl', function ($scope, $dialog, LiebautServer) {
        
        /*Restangular.all('language').getList().then(function (languages) {
            console.log(languages);
        }) ;
              */
    $scope.languages = [{id:1, name:'Nederlands Test'}];
	$scope.suppliers = [{
		supplierNumber: 1,
		name: 'Test',
		language: {
			name: 'Nederlands',
			languageCode: 'NL'},
		addresses: [{
			street: 'Test Straat',
			streetNumber: 17,
			box: 'A',
			postalCode: '9300',
			location: 'Aalst',
			country: {
				name: 'Belgie',
				countryCode: 'BE'},
			type: {
				name: 'Facturatie'}}],
		telecom: [{
			value: 'joris.desmedt@evs.com',
			type: {
				name: 'E-mail'}},
			{value: '053/783555',
			type: {
				name: 'Telefoon'}}]
		}];
	
	$scope.telecomData = [];
	$scope.removeTelecomBtn = '<button id="editBtn" type="button" class="btn btn-link" ng-click="removeTelecom(row.rowIndex)" >Verwijderen</button>'
	$scope.gridOptions = {
			data: 'telecomData',
			enableCellSelection: true,
			enableRowSelection: false,
            displaySelectionCheckbox: false,
            enableCellEdit: true,
            multiSelect: false,
            columnDefs: [{field: 'type.name', displayName: 'Type', enableCellEdit: true},
                         {field:'value', displayName:'Waarde', enableCellEdit: true},
                         {displayName:'', width:'100px', cellTemplate: $scope.removeTelecomBtn}]};
	
	$scope.newType = '';
	$scope.newValue = '';
	$scope.addTelecom = function(){
		if($scope.newType && $scope.newValue.length > 0){
			var t = {type: $scope.newType, value: $scope.newValue};
			$scope.telecomData.push(t);
		}
	};
	
	$scope.removeTelecom = function(index){
		$scope.telecomData.splice(index,1);
	};
	$scope.emptyAddress = {
			street: '',
			streetNumber: 0,
			box: '',
			postalCode: '',
			location: '',
			country: {
				name: 'Belgie',
				countryCode: 'BE'},
			type: {
				name: 'Adres'}};
	$scope.selectedAddress = 0;
	$scope.addresses = [JSON.parse(JSON.stringify($scope.emptyAddress))];
	$scope.addAddress = function(){
		$scope.addresses.push(JSON.parse(JSON.stringify($scope.emptyAddress)));
		$scope.selectedAddress = $scope.addresses.length-1;
	}
	$scope.changeAddressTab = function(index){
		$scope.selectedAddress = index;
	}
	
	$scope.removeAddress = function(index){
		$scope.addresses.splice(index,1);
		$scope.selectedAddress = 0;
	}

    $scope.init = function() {
         LiebautServer.getAll('language', null)
               .success(function(response, error)
                    {
                        $scope.languages = response;
                    });
        LiebautServer.getAll('country', null)
            .success(function(response, error)
            {
                $scope.countries = response;
            })
        LiebautServer.getAll('addressType', null)
            .success(function(response, error)
            {
                $scope.addressTypes = response;
            })
        LiebautServer.getAll('telecomType', null)
            .success(function(response, error)
            {
                $scope.telecomTypes = response;
            })
    }

    $scope.saveSupplier = function(){
        var supplier = {};
        supplier.number = $scope.number;
        supplier.name = $scope.name;
        supplier.language = {id: $scope.selectedLanguage};
        supplier.telecom = [];
        for(var i=0; i<$scope.telecomData.length; i++){
            var telecom = $scope.telecomData[i];
            var newTelecom = {};
            newTelecom.value = telecom.value
            newTelecom.telecomType = {id: telecom.type.id}
            supplier.telecom.push(newTelecom);
        }
        var addresses = [];
        for(var i=0; i<$scope.addresses.length; i++){
            var address = $scope.addresses[i];
            var newAddress = {};
            newAddress.street = address.street;
            newAddress.number = address.number;
            newAddress.postalCode = address.postalCode;
            newAddress.bus = address.bus;
            newAddress.location = address.location;
            newAddress.country = {id: address.country.id};
            newAddress.addressType= {id: address.type.id};
            newAddress.defaultAddress = (i==0);
            addresses.push(newAddress);
        }
        supplier.addresses = addresses;



        LiebautServer.save('supplier', supplier)
            .success(function(response, error)
            {
               if(error)
                   alert("Error saving supplier");
               else
                   alert("Success saving supplier");
            })
    }

    $scope.init();
});

myApp.controller('ArticleCtrl', function ($scope, $dialog, LiebautServer, AlertService) {
	$scope.sizes = [];
	$scope.models = [];
	$scope.ean = [];
    $scope.prices = [];
    $scope.purchases = [];
    $scope.priceClasses = [];
    $scope.suppliers = [];


    $scope.childrenSizes = [{name: '98'},{name: '104'},{name: '116'},{name: '128'},{name: '140'},{name: '152'},{name: '164'}];
    $scope.womenSizes = [{name: '34'},{name: '36'},{name: '38'},{name: '40'},{name: '42'},{name: '44'},{name: '46'}];
    $scope.menSizes = [{name: '48'},{name: '50'},{name: '52'},{name: '54'},{name: '56'},{name: '58'},{name: '60'}];
	
	$scope.addSize = function(){
		if($scope.newSize && $scope.newSize.length != 0){
			var s = {name: $scope.newSize};
			$scope.sizes.push(s);
		}
	}
	$scope.removeSize = function(index){
		$scope.sizes.splice(index,1);
	}

    $scope.addSizes = function(sizes){
        $scope.sizes = $scope.sizes.concat(sizes);
    }
	$scope.removeSizeBtn = '<button id="editBtn" type="button" class="btn btn-link" ng-click="removeSize(row.rowIndex)" >Verwijderen</button>'
	$scope.gridSizeOptions = {
			data: 'sizes',
			enableCellSelection: true,
			enableRowSelection: false,
            displaySelectionCheckbox: false,
            enableCellEdit: true,
            multiSelect: false,
            columnDefs: [{field: 'name', displayName: 'Maat', enableCellEdit: true},
                         {displayName:'', width:'100px', cellTemplate: $scope.removeSizeBtn}]};
	
	$scope.addModel = function(){
		if($scope.newModel && $scope.newModel.length != 0 && $scope.newModelDescription && $scope.newModelDescription.length != 0){
			var s = {code: $scope.newModel, name: $scope.newModelDescription};
			$scope.models.push(s);
		}
	}
	$scope.removeModel = function(index){
		$scope.models.splice(index,1);
	}
	$scope.removeModelBtn = '<button id="editBtn" type="button" class="btn btn-link" ng-click="removeModel(row.rowIndex)" >Verwijderen</button>'
	$scope.gridModelOptions = {
			data: 'models',
			enableCellSelection: true,
			enableRowSelection: false,
            displaySelectionCheckbox: false,
            enableCellEdit: true,
            multiSelect: false,
            columnDefs: [{field: 'code', displayName: 'Model', enableCellEdit: true},
                         {field: 'name', displayName: 'Omschrijving', enableCellEdit: true},
                         {displayName:'', width:'100px', cellTemplate: $scope.removeModelBtn}]};
	
	$scope.addEan = function(){
		if($scope.newEan && $scope.newEan.length != 0){
			var s = {eanCode: $scope.newEan, size: $scope.newEanSize, model: $scope.newEanModel};
			$scope.ean.push(s);
		}
	}
	$scope.removeEan = function(index){
		$scope.ean.splice(index,1);
	}
	$scope.removeEanBtn = '<button id="editBtn" type="button" class="btn btn-link" ng-click="removeEan(row.rowIndex)" >Verwijderen</button>'
	$scope.gridEanOptions = {
			data: 'ean',
			enableCellSelection: true,
			enableRowSelection: false,
            displaySelectionCheckbox: false,
            enableCellEdit: true,
            multiSelect: false,
            columnDefs: [{field: 'eanCode', displayName: 'EANcode', enableCellEdit: true},
                         {field: 'size.name', displayName: 'Maat', enableCellEdit: true},
                         {field: 'model.code', displayName: 'Model', enableCellEdit: true},
                         {displayName:'', width:'100px', cellTemplate: $scope.removeEanBtn}]};

    $scope.removePriceBtn = '<button id="editBtn" type="button" class="btn btn-link" ng-click="removePrice(row.rowIndex)" >Verwijderen</button>'
    $scope.gridPriceOptions = {
        data: 'prices',
        enableCellSelection: true,
        enableRowSelection: false,
        displaySelectionCheckbox: false,
        enableCellEdit: true,
        multiSelect: false,
        columnDefs: [
            {field: 'factor', displayName: 'Coefficient', enableCellEdit: true},
            {field: 'computedPrice', displayName: 'Berekende prijs', enableCellEdit: false},
            {field: 'price', displayName: 'Aangepaste prijs', enableCellEdit: true},
            {field: 'priceClass.name', displayName: 'Prijscategorie', enableCellEdit: true},
            {field: 'size.name', displayName: 'Maat', enableCellEdit: true},
            {field: 'model.code', displayName: 'Model', enableCellEdit: true},
            {displayName:'', width:'100px', cellTemplate: $scope.removeEanBtn}]};

    $scope.addPrice = function(){
        if($scope.newPrice && $scope.newPrice.length != 0 && $scope.newFactor && $scope.newFactor.length != 0){
            var s = {   factor: $scope.newFactor,
                        computedPrice: $scope.computedPrice,
                        price: $scope.newPrice,
                        priceClass: $scope.newPriceClass,
                        size: $scope.newPriceSize,
                        model: $scope.newPriceModel};
            $scope.prices.push(s);
        }
    }




    $scope.addPurchase = function(){
        if($scope.newPurchase && $scope.newPurchase.length != 0 && $scope.newDiscount && $scope.newDiscount.length != 0){
            var s = {price: $scope.newPurchase, discount: $scope.newDiscount, size: $scope.newPurchaseSize, model: $scope.newPurchaseModel};
            $scope.purchases.push(s);
        }
    }
    $scope.removePurchase = function(index){
        $scope.purchases.splice(index,1);
    }


    $scope.removePurchaseBtn = '<button id="editBtn" type="button" class="btn btn-link" ng-click="removePurchase(row.rowIndex)" >Verwijderen</button>'
    $scope.gridPurchaseOptions = {
        data: 'purchases',
        enableCellSelection: true,
        enableRowSelection: false,
        displaySelectionCheckbox: false,
        enableCellEdit: true,
        multiSelect: false,
        columnDefs: [{field: 'price', displayName: 'Aankoopprijs', enableCellEdit: true},
            {field: 'discount', displayName: 'Korting', enableCellEdit: true},
            {field: 'size.name', displayName: 'Maat', enableCellEdit: true},
            {field: 'model.code', displayName: 'Model', enableCellEdit: true},
            {displayName:'', width:'100px', cellTemplate: $scope.removePurchaseBtn}]};


    $scope.newPriceSize = null;
    $scope.newPriceModel = null;
    $scope.$watch('newFactor', function(newVal, oldVal) {
        if($scope.purchases.length > 0){
            var purchase = searchPurchaseMatch($scope.newPriceSize, $scope.newPriceModel).price;
            $scope.computedPrice = newVal * purchase;
        }
    });

    var searchPurchaseMatch = function(size, model){
        for(var i=0; i<$scope.purchases.length; i++){
            var purchase = $scope.purchases[i];
            var equalSize;
            var equalModel;
            var general;
            if(purchase.size == size && purchase.model == model)
                return purchase;
            else if(purchase.size = size && !equalSize)
                equalSize = purchase;
            else if(purchase.model = model && !equalModel)
                equalModel = purchase;
            else if(!purchase.model && !purchase.size)
                general = purchase;
        }

        if(equalSize)
            return equalSize
        else if(equalModel)
            return equalModel
        else
            return general;
    }

    $scope.init = function(){
        LiebautServer.getAll("priceClass", null).success(
            function(response){
                $scope.priceClasses = response;
            });
        LiebautServer.getAll("supplier", null).success(
            function(response){
                $scope.suppliers = response;
            });
    }

    $scope.init();

    $scope.checkArticleNumber = function(){
        if(!$scope.lastLoaded || !($scope.lastLoaded.supplier == $scope.supplier.number && $scope.lastLoaded.articleNumber == $scope.articleNumber)){
            LiebautServer.getAll("article", {"articleNumber": $scope.articleNumber, "supplier":$scope.supplier.number}).success(
                function(response){
                    if(response.length >= 1){
                        var article = response[0];
                        $scope.description = article.description;
                        $scope.models = article.models;
                        $scope.sizes = article.sizes;
                        $scope.ean = article.eanCodes;
                        $scope.purchases = article.purchaseDetails;
                        $scope.prices = article.prices;

                        $scope.lastLoaded = {supplier: $scope.supplier.number, articleNumber: $scope.articleNumber}
                        AlertService.add("success", "Artikel " +article.supplier.number+"/"+article.articleNumber+ " geladen.", 3000);
                    } else{
                        $scope.lastLoaded = null;
                    }
                }
            )
        }

    }

    $scope.saveArticle = function(){
        var article = {};
        article.supplier = $scope.supplier;
        article.articleNumber = $scope.articleNumber;
        article.description = $scope.description;

        article.models = $scope.models;
        article.sizes = $scope.sizes;
        article.eanCodes = $scope.ean;
        article.purchaseDetails = $scope.purchases;
        article.prices = $scope.prices;
        for(var i=0; i <  article.prices.length; i++){
             delete article.prices[i].computedPrice;
        }


        LiebautServer.save("article", article).success(
            function(response){
                alert("Article saved");
            }).error(
            function(response){
                alert("Error: Article not saved");
            });



    }


});

myApp.controller('ArticlePriceCtrl', function ($scope, $dialog, $routeParams, LiebautServer, AlertService) {

    $scope.priceClass = {};
    $scope.supplier = "";
    $scope.articleNumber = "";
    $scope.description = "";
    $scope.prices = [];
    $scope.loadPriceClass = function(){
        LiebautServer.get("priceClass", $routeParams.priceClass, null).success(
            function(response){
                $scope.priceClass = response;
            }
        )
    }

    $scope.valutaFormat = '<div class="ngCellText">€ {{row.getProperty(col.field) | number:2}}</div>'
    $scope.gridPrices = {
        data: 'prices',
        enableCellSelection: false,
        enableRowSelection: true,
        displaySelectionCheckbox: false,
        enableCellEdit: false,
        multiSelect: false,
        columnDefs: [{field: 'size.name', displayName: 'Maat'},
            {field: 'model.code', displayName: 'Model'},
            {field:'price', displayName: 'Prijs', cellTemplate: $scope.valutaFormat}
        ]};

    $scope.searchArticle = function(){
        $scope.prices = [];
        LiebautServer.getAll("article", {"articleNumber":$scope.articleNumber, "supplier":$scope.supplier}).success(
            function(response){
                if(response.length == 0){
                    AlertService.add("error", "Artikel " +$scope.supplier+"/"+$scope.articleNumber+ " niet gevonden.", 5000)
                } else{
                    var prices = [];
                    var article = response[0];
                    $scope.description = article.description;
                    for(var i=0; i < article.prices.length; i++){
                        var price = article.prices[i];
                        if(price.priceClass.id == $scope.priceClass.id){
                            prices.push(price);
                        }
                        if(prices.length > 0){
                            $scope.prices = prices;
                        } else {
                            AlertService.add("error", "Artikel " +$scope.supplier+"/"+$scope.articleNumber+ " gevonden, maar geen prijs in deze prijsklasse gevonden.", 5000)
                        }
                    }
                }
            }
        )
    }

    $scope.loadPriceClass();

} );

myApp.controller('CustomerCtrl', function ($scope, $dialog, LiebautServer) {

    /*Restangular.all('language').getList().then(function (languages) {
     console.log(languages);
     }) ;
     */
    $scope.languages = [];
    $scope.priceClasses = [];
    $scope.telecomData = [];
    $scope.removeTelecomBtn = '<button id="editBtn" type="button" class="btn btn-link" ng-click="removeTelecom(row.rowIndex)" >Verwijderen</button>'
    $scope.gridOptions = {
        data: 'telecomData',
        enableCellSelection: true,
        enableRowSelection: false,
        displaySelectionCheckbox: false,
        enableCellEdit: true,
        multiSelect: false,
        columnDefs: [{field: 'type.name', displayName: 'Type', enableCellEdit: true},
            {field:'value', displayName:'Waarde', enableCellEdit: true},
            {displayName:'', width:'100px', cellTemplate: $scope.removeTelecomBtn}]};

    $scope.newType = '';
    $scope.newValue = '';
    $scope.addTelecom = function(){
        if($scope.newType && $scope.newValue.length > 0){
            var t = {type: $scope.newType, value: $scope.newValue};
            $scope.telecomData.push(t);
        }
    };

    $scope.removeTelecom = function(index){
        $scope.telecomData.splice(index,1);
    };
    $scope.emptyAddress = {
        street: '',
        streetNumber: 0,
        box: '',
        postalCode: '',
        location: '',
        country: {
            name: 'Belgie',
            countryCode: 'BE'},
        type: {
            name: 'Adres'}};
    $scope.selectedAddress = 0;
    $scope.addresses = [JSON.parse(JSON.stringify($scope.emptyAddress))];
    $scope.addAddress = function(){
        $scope.addresses.push(JSON.parse(JSON.stringify($scope.emptyAddress)));
        $scope.selectedAddress = $scope.addresses.length-1;
    }
    $scope.changeAddressTab = function(index){
        $scope.selectedAddress = index;
    }

    $scope.removeAddress = function(index){
        $scope.addresses.splice(index,1);
        $scope.selectedAddress = 0;
    }

    $scope.init = function() {
        LiebautServer.getAll('language', null)
            .success(function(response, error)
            {
                $scope.languages = response;
            });
        LiebautServer.getAll('country', null)
            .success(function(response, error)
            {
                $scope.countries = response;
            })
        LiebautServer.getAll('addressType', null)
            .success(function(response, error)
            {
                $scope.addressTypes = response;
            })
        LiebautServer.getAll('telecomType', null)
            .success(function(response, error)
            {
                $scope.telecomTypes = response;
            })
        LiebautServer.getAll('priceClass', null)
            .success(function(response, error)
            {
                $scope.priceclasses = response;
            })
    }

    $scope.saveCustomer = function(){
        var customer = {};
        customer.number = $scope.number;
        customer.name = $scope.name;
        customer.language = {id: $scope.selectedLanguage};
        customer.vatNumber = $scope.vatNumber;
        customer.extraName = $scope.extraName;
        customer.priceClass = {id: $scope.selectedPriceClass};
        customer.discount = $scope.discount;
        customer.telecom = [];
        for(var i=0; i<$scope.telecomData.length; i++){
            var telecom = $scope.telecomData[i];
            var newTelecom = {};
            newTelecom.value = telecom.value
            newTelecom.telecomType = {id: telecom.type.id}
            customer.telecom.push(newTelecom);
        }
        var addresses = [];
        for(var i=0; i<$scope.addresses.length; i++){
            var address = $scope.addresses[i];
            var newAddress = {};
            newAddress.street = address.street;
            newAddress.number = address.number;
            newAddress.postalCode = address.postalCode;
            newAddress.bus = address.bus;
            newAddress.location = address.location;
            newAddress.country = {id: address.country.id};
            newAddress.addressType= {id: address.type.id};
            newAddress.defaultAddress = (i==0);
            addresses.push(newAddress);
        }
        customer.addresses = addresses;



        LiebautServer.save('customer', customer)
            .success(function(response, error)
            {
                if(error)
                    alert("Error saving supplier");
                else
                    alert("Success saving supplier");
            })
    }

    $scope.init();
});

myApp.controller('NewDeliveryOrder', function ($scope, $dialog, $timeout, LiebautServer) {
    $scope.articleDetails = [];
    $scope.sizes = [];
    $scope.models = [];
    $scope.priceClasses = [];

    $scope.amount = 1;
    $scope.individualDiscount = 0;
    $scope.generalDiscount = 0;
    $scope.priceClass = {};
    $scope.priceClass.id = 1;
    $scope.article = {};
    $scope.customer = {};
    $scope.priceClass = {};

    $scope.orderGrid = {
        data: 'articleDetails',
        enableCellSelection: false,
        enableRowSelection: true,
        displaySelectionCheckbox: false,
        enableCellEdit: false,
        multiSelect: false,
        columnDefs: [{field: 'article.supplier.number', displayName: 'Fabrikant', enableCellEdit: false},
            {field:'article.articleNumber', displayName:'Artikel Nummer', enableCellEdit: false},
            {field:'size.name', displayName:'Maat', enableCellEdit: false},
            {field:'model.code', displayName:'Model', enableCellEdit: false},
            {field:'description', displayName:'Omschrijving', enableCellEdit: false},
            {field:'amount', displayName:'Aantal', enableCellEdit: true},
            {field:'price', displayName:'Prijs', enableCellEdit: true},
            {field:'discount', displayName:'Korting', enableCellEdit: true},
            {displayName:'', width:'100px', cellTemplate: $scope.removeTelecomBtn}]};
    $scope.getArticle = function(){
        if($scope.articleNumber && $scope.supplier){
            LiebautServer.getAll("article", {"articleNumber": $scope.articleNumber, "supplier":$scope.supplier}).success(
                function(data){
                    if(data.length > 0){
                        var article =data[0];
                        $scope.sizes = article.sizes;
                        if($scope.sizes.length > 0){
                            $scope.sizes.sort(orderSizes);
                            $scope.size = $scope.sizes[0];
                            $scope.form.size.focus();
                        }
                        $scope.models = article.models;
                        if($scope.models.length > 0){
                            $scope.models.sort(orderModels);
                            $scope.model = $scope.models[0];
                        }

                        $scope.description = article.description;
                        var prices = [];
                        for(var i=0; i < article.prices.length; i++){
                            var price = article.prices[i];
                            if(price.priceClass.id == $scope.priceClass.id){
                                prices.push(price);
                            }
                        }
                        if(prices.length > 0){
                            $scope.price = (searchPriceMatch($scope.size, $scope.model, prices)).price.toFixed(2);
                        } else {
                            AlertService.add("error", "Artikel " +$scope.supplier+"/"+$scope.articleNumber+ " gevonden, maar geen prijs in deze prijsklasse gevonden.", 5000)
                        }

                        $scope.article = article;
                    }



                }
            )
        }
    }

    $scope.getCustomer = function(){
        if($scope.customerNumber){
            LiebautServer.getAll("customer", {"number": $scope.customerNumber}).success(
                function(data){
                    if(data.length > 0){
                        $scope.customer = data[0];
                        $scope.generalDiscount = $scope.customer.discount;
                        for(var i = 0; i < $scope.priceClasses.length; i++){
                            if($scope.customer.priceClass.id == $scope.priceClasses[i].id)
                                $scope.priceClass = $scope.priceClasses[i];
                        }
                    } else
                        $scope.customer = {};
                }).error(
                    function(data){
                        $scope.customer = {};
                    }
                );
        } else
            $scope.customer = {}
    }

    $scope.addArticle = function(){
        var articleDetails = {};
        articleDetails.article = $scope.article;
        articleDetails.description = $scope.article.description + ($scope.models.length > 0 ? " - " + $scope.model.name : "");
        articleDetails.size = $scope.size;
        articleDetails.model = $scope.model;
        articleDetails.price = $scope.price;
        articleDetails.discount = $scope.individualDiscount;
        articleDetails.amount = $scope.amount;
        $scope.articleDetails.push(articleDetails);
        $timeout(function () {
            var grid = $scope.orderGrid.ngGrid;
            grid.$viewport.scrollTop(($scope.articleDetails.length -1) * grid.config.rowHeight);
        },0);
    }

    $scope.init = function(){
        LiebautServer.getAll("priceClass", null).success(
            function(data){
                if(data.length > 0){
                    $scope.priceClasses = data;
                    $scope.priceClass = $scope.priceClasses[0];
                }
            });
    }

    $scope.init();

    var orderSizes = function(sizeA, sizeB){
        var defaultSizes = ['XS', 'S', 'M', 'L', 'XL', 'XXL', 'XXXL']
        var sizeNameA = sizeA.name;
        var sizeNameB = sizeB.name;
        var indexOfA = sizeNameA.indexOf("/");
        var indexOfB = sizeNameB.indexOf("/");
        if(indexOfA > -1)
            sizeNameA = sizeNameA.substr(0, indexOfA);
        if(indexOfB > -1)
            sizeNameB = sizeNameB.substr(0, indexOfB);
        try{
            var sizeNumberA = parseInt(sizeNameA)
            var sizeNumberB = parseInt(sizeNameB)
            return sizeNumberA - sizeNumberB;
        } catch(error) {
            var sizeNumberA = defaultSizes.indexOf(sizeNumberA.toUpperCase());
            var sizeNumberB = defaultSizes.indexOf(sizeNumberB.toUpperCase());
            return sizeNumberA - sizeNumberB;
        }
    }

    var orderModels = function(modelA, modelB){
        var modelCodeA = modelA.code;
        var modelCodeB = modelB.code;
        try{
            var numberCodeA = parseInt(modelCodeA)
            var numberCodeB = parseInt(modelCodeB)
            if(!isNaN(numberCodeA) && !isNaN(numberCodeB))
                return numberCodeA - numberCodeB;
            else{
                if(modelCodeA < modelCodeB)
                    return -1
                else if(modelCodeA > modelCodeB)
                    return 1
                else
                    return 0
            }
        } catch(error) {
            if(modelCodeA < modelCodeB)
                return -1
            else if(modelCodeA > modelCodeB)
                return 1
            else
                return 0
        }
    }

    var searchPriceMatch = function(size, model, prices){
        for(var i=0; i<prices.length; i++){
            var price = prices[i];
            var equalSize;
            var equalModel;
            var general;
            if(price.size == size && price.model == model)
                return price;
            else if(price.size == size && !equalSize)
                equalSize = price;
            else if(price.model == model && !equalModel)
                equalModel = price;
            else if(!price.model && !price.size)
                general = price;
        }

        if(equalSize)
            return equalSize
        else if(equalModel)
            return equalModel
        else
            return general;
    }
});

function CloseDialogController($scope, dialog){
	  $scope.close = function(result, ok){
		  if(ok)
			  dialog.close(result);
		  else
			  dialog.close(null);
	  };
	}


